package club.emergency.wechat.manager.search.provider.impl;

import club.emergency.wechat.common.response.ResponseEntity;
import club.emergency.wechat.common.response.StatusCode;
import club.emergency.wechat.manager.search.ManagerSearch;
import club.emergency.wechat.model.authorization.AuthorizationHasRole;
import club.emergency.wechat.model.manager.Manager;
import club.emergency.wechat.persistence.authorization.AuthorizationHasRoleMapper;
import club.emergency.wechat.persistence.authorization.AuthorizationMapper;
import club.emergency.wechat.persistence.manager.ManagerMapper;
import club.emergency.wechat.sso.jwt.JwtTokenUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Create with IntelliJ IDEA
 * Project Name: wechat
 * Package Name: club.emergency.wechat.manager.search.provider.impl
 * Date: 2018/12/5
 *
 * @author: 快乐的小菌菌
 * Description:
 */
@Slf4j
@RestController
public class ManagerSearchImpl implements ManagerSearch {

    private ManagerMapper managerMapper;

    private AuthorizationHasRoleMapper authorizationHasRoleMapper;

    private AuthorizationMapper authorizationMapper;

    @Value("${jwt.secretKey}")
    private String secretKey;

    @Value("${jwt.accessTokenExpired}")
    private long accessTokenExpired;

    @Value("${jwt.refreshTokenExpired}")
    private long refreshTokenExpired;

    public ManagerSearchImpl(ManagerMapper managerMapper, AuthorizationHasRoleMapper authorizationHasRoleMapper, AuthorizationMapper authorizationMapper) {
        this.managerMapper = managerMapper;
        this.authorizationHasRoleMapper = authorizationHasRoleMapper;
        this.authorizationMapper = authorizationMapper;
    }

    @Override
    public String flipList(@RequestParam("pageNo") Integer pageNo, @RequestParam("pageSize") Integer pageSize) {
        Page<Manager> page = new Page<>(pageNo, pageSize);
        IPage<Manager> staffIPage = managerMapper.selectPage(page, null);
        return ResponseEntity.ok(StatusCode.DB_SEARCH_OK, "数据查询成功", staffIPage);
    }

    @Override
    public String login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        queryWrapper.eq("password", password);
        Manager manager = this.managerMapper.selectOne(queryWrapper);
        if (Objects.isNull(manager)) {
            return ResponseEntity.error(StatusCode.LOGIN_ERROR, "登录失败，用户名密码错误！");
        } else {
            List<Long> roleList = managerMapper.queryRoleIdFromRHMByManagerId(manager.getId());
            if (roleList.size() != 0) {
                QueryWrapper<AuthorizationHasRole> aHRWrapper = new QueryWrapper<>();
                aHRWrapper.in("role_id", roleList);
                List<AuthorizationHasRole> authorizationHasRoles = authorizationHasRoleMapper.selectList(aHRWrapper);
                if (authorizationHasRoles.size() != 0) {
                    List<Long> authorizationIdList = new ArrayList<>();
                    authorizationHasRoles.forEach(authorizationHasRole -> {
                        authorizationIdList.add(authorizationHasRole.getAuthorizationId());
                    });
                    manager.setAuthorizationList(authorizationMapper.selectBatchIds(authorizationIdList));
                }
            }
            TokenModel tokenModel = createToken(manager.getId());
            //在每次登录的时候需要把manager对象传到内部对象中。注意：并不是放在jwt token中，仅仅是以变量形式传参，方便前台解析
            tokenModel.setManager(manager);
            return ResponseEntity.ok(StatusCode.LOGIN_OK, "登录成功！", tokenModel);
        }
    }

    @Override
    public String updateToken(@RequestParam("id") Long id) {
        log.info("id：" + id + "的用户请求更新Token");
        return ResponseEntity.ok(StatusCode.AUTHORIZATION_UPDATE_OK, "Token更新成功！", createToken(id));
    }

    @Override
    public String getById(@RequestParam("id") Long id) {
        Manager manager = managerMapper.selectById(id);
        if (Objects.isNull(manager)) {
            return ResponseEntity.error(StatusCode.DB_SEARCH_ERROR, "没有id为:" + id + "的人员信息");
        }
        return ResponseEntity.ok(StatusCode.DB_SEARCH_OK, "根据id查询人员成功!", manager);
    }

    private TokenModel createToken(Long id) {
        String accessToken = JwtTokenUtil.createJWT(secretKey, String.valueOf(id), "accessToken", accessTokenExpired);
        String refreshToken = JwtTokenUtil.createJWT(secretKey, String.valueOf(id), "refreshToken", refreshTokenExpired);
        return new TokenModel(accessToken, refreshToken, null);
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private class TokenModel {
        private String accessToken;
        private String refreshToken;
        private Manager manager;
    }
}
